/*
 * Buffer.cpp
 *
 *  Created on: 2012-9-3
 *      Author: yangentao@gmail.com
 */

#include "TextBuffer.h"

TextVector::TextVector() :
		SplitVec<char>(512) { //TODO 8->512
}
AutoActionGroup::AutoActionGroup(TextBuffer* textBuffer_) {
	textBuffer = textBuffer_;
	textBuffer->actionMgr.beginGroup();
}
AutoActionGroup::~AutoActionGroup() {
	textBuffer->actionMgr.endGroup();
}

TextBuffer::TextBuffer() {
	actionMgr.setTextReplacable(this);
	addTextListener(&lineMgr);
	addTextListener(&posMgr);
}
TextBuffer::~TextBuffer() {

}

void TextBuffer::addTextListener(TextListener* textListener) {
	textListeners.append(textListener);
}

String TextBuffer::getText(int position, int length) const {
	String s(length);
	text.getRange(s.buffer(), position, length);
	s.setLength(length);
	return s;
}

String TextBuffer::getText()const{
	return getText(0, length());
}
void TextBuffer::setText(String text){
	doAction(Action(0, length(), text));
}

String TextBuffer::textReplace(int from, int removeLength, const String& insertText) {
	int insertLength = insertText.length();
	String removedText = getText(from, removeLength);
	text.replace(from, removeLength, insertText.buffer(), insertLength);
	for (int i = 0; i < textListeners.size(); ++i) {
		textListeners[i]->onTextReplaced(from, removedText, insertText);
	}
	return removedText;
}

